var door = {};
var app = getApp();
var door_id = '';
var lockData = '';
var has_reconnect = false;
var realDoorDeviceId = '';
var autoOpenDoorTimer = null;
var devicesArr = [];
var isOpened = false;
var doorNotFindTimer = null;
var common = require('./common.js');
door.getDoorList = (_this) => {
	if (app.globalData.is_login && app.globalData.config && app.globalData.config.house.house_door && app.globalData.config
		.house.house_door == '1') {
		common.post('House&a=user_visitor_open_list', {
			noTip: true,
			open_type: 'index'
		}, function(result) {
			if (result.open_list_info) {
				wx.setStorageSync('user_visitor_open_list', result);
			}
			wx.setStorageSync('user_door_list', result.door_info);
			console.log('doorList', result);
			console.log('is_automatic_open_door' + _this.is_automatic_open_door + 'door_share_id' + app.globalData.door_share_id);
			var addMySmallProgram = wx.getStorageSync('addMySmallProgram');
			
			_this.doorList = result.door_info;
			_this.addMySmallProgram = addMySmallProgram ? true : false;
			_this.is_btn = result.is_btn;
			if (app.globalData.door_share_id != '') {
				door.door_share_info(_this)
			} else {
				//是否自动开门
				if (app.globalData.is_login) {
					door.auto_open_door(_this)
				}
			}

		});
	}
}

door.door_share_info = (_this) => {
	//获取门禁分享信息
	if (app.globalData.is_login) {
		console.log('获取门禁分享信息')
		common.post('Login&a=door_share_info', {
			door_share_id: app.globalData.door_share_id
		}, (data) => {
			console.log('门禁分享信息列表')
			if (!data.is_owner) {
				//不是自己的
				if (data.is_over) {
					//已过期 解除绑定
					wx.showModal({
						title: '提示',
						content: '您的好友分享您一个临时开门权限已失效',
						showCancel: false,
						complete(res) {
							//解除用户绑定的所有超过时间限制的分享门禁信息关联
							_this.show_openDoor = true;
							app.globalData.door_share_id = '';
							door.auto_open_door(_this)
							door.relieve_bind_all_share_user(_this, true)
						}
					})
				} else {
					wx.showModal({
						title: '提示',
						content: '您的好友分享您一个临时开门权限，是否现在去开门',
						success(res) {
							_this.show_openDoor = true;

							if (res.confirm) {
								if (app.globalData.is_login) {
									_this.redirect = '';
									app.globalData.door_share_id = '';
									door.open_share_door(_this)
								} else {
									_this.showAuthBtn = true;
								}
							}
							if (res.cancel) {
								wx.showModal({
									title: '提示',
									showCancel: false,
									content: '您可以点击右下角开门按钮去开门',
									success(res) {
										app.globalData.door_share_id = '';
										door.auto_open_door(_this)
										//解除用户绑定的所有超过时间限制的分享门禁信息关联
										door.relieve_bind_all_share_user(_this, false)

									}
								})
							}
						}
					})
				}
			} else {
				app.globalData.door_share_id = '';
				door.auto_open_door(_this)
			}
		});
	}
}

door.relieve_bind_all_share_user = function(_this, type) {
	//解除用户绑定的所有超过时间限制的分享门禁信息关联
	common.post('Login&a=relieve_bind_all_share_user', {}, () => {}, _this);
}

door.auto_open_door = (_this) => {
	//是否自动开门
	console.log('是否自动开门:' + _this.open_door_type)
	if (wx.getStorageSync('auto_door_open') == '') {
		common.post('Login&a=auto_open_door_info', {}, (data) => {
			wx.setStorageSync('auto_door_open', data.auto_door_open ? '1' : '0');
		})
	} else {
		door.is_auto_open_door(_this)
	}
}

door.is_auto_open_door = (_this) => {
	var $open_door = wx.getStorageSync('auto_door_open');
	_this.open_door_type = app.globalData.open_door_type ? $open_door == 1 ? true : false : false;
	_this.is_automatic_open_door = app.globalData.open_door_type ? $open_door == 1 ? true : false : false;
	if ((_this.redirect == 'openDoor' || $open_door == 1) && app.globalData.open_door_type) {
		console.log(app.globalData.open_door_type, app.globalData.door_share_id)
		//进入自动开门
		// #ifdef MP-WEIXIN
		wx.setKeepScreenOn({
			keepScreenOn: true,
			success: function() {
				console.log("设置屏幕状态保持常亮成功")
			},
			fail: function() {
				console.log("设置屏幕状态保持常亮失败")
			}
		})
		// #endif
		door.openIngDoor(_this);
		_this.redirect = '';
	} else {
		// #ifdef MP-WEIXIN
		wx.setKeepScreenOn({
			keepScreenOn: false,
			success: () => {
				console.log("取消屏幕状态保持常亮成功")
			},
			fail: () => {
				console.log("取消屏幕状态保持常亮失败")
			}
		})
		// #endif
	}
}


door.openIngDoor = function(_this, e, type) {
	if (autoOpenDoorTimer) {
		clearTimeout(autoOpenDoorTimer);
	}
	if (!_this.hide) {
		if (typeof e == 'object') {
			common.upFormid(e);
		}
		console.log(app.globalData.is_login, app.globalData.userInfo);
		if (!app.globalData.userInfo) {
			uni.hideLoading();
			wx.showModal({
				title: '温馨提示',
				content: '正在获取您的账号信息，请稍等一会再试',
				showCancel: false
			});

			return false;
		}
		if (!app.globalData.userInfo.phone || app.globalData.userInfo.phone == '') {
			wx.hideLoading();
			wx.showModal({
				title: '温馨提示',
				content: '开门请先注册手机号哦。',
				showCancel: true,
				success: function(res) {
					if (res.confirm) {
						_this.redirect = 'openDoor';
						wx.navigateTo({
							url: '/pages/my/newnumber',
						})
					}
				}
			});

			return false;
		}

		if (_this.doorList.length == 0 && !_this.is_btn) {
			uni.hideLoading();
			if (type) {
				var tmpVillage = uni.getStorageSync("village_key");
				if(tmpVillage.pigcms_id){
					wx.showModal({
						title: '温馨提示',
						content: "您没有门禁权限，请联系小区物业。",
						showCancel: false
					});
				}else{
					wx.showModal({
						title: '温馨提示',
						content: "您没有门禁权限，请检查是否绑定为小区业主或家属。点击确定键，前往绑定。",
						showCancel: true,
						success: function(res) {
							if (res.confirm) {
								common.parseUrl('url/House/village_list', '', false, '小区列表');
							}
						}
					});
				}
			}
			return false;
		}
		if (type) {
			door.open_share_door(_this)
		} else {
			if (this.open_door_type && app.globalData.open_door_type) {
				door.openBlue(_this)
			}
		}
		uni.hideLoading();
	}
}

door.open_share_door = (_this) => {
	app.globalData.door_share_id = '';
	wx.navigateTo({
		url: "/pages/share/share"
	});

}


door.openBlue = function(_this) {
	if (!_this.hide) {
		realDoorDeviceId = '';
		wx.openBluetoothAdapter({
			success: function(res) {
				_this.open_door_index = 1;
				_this.openBlueNum = true;
				//六秒钟关闭搜索
				doorNotFindTimer = setTimeout(function() {
					wx.hideToast();
					if (isOpened == false && !_this.hide) {
						door.stopBluetoothDevicesDiscovery(_this);
						door.closeBluetoothAdapter(_this);

						app.log_report({
							msg: '扫描门禁失败',
							devicesArr: devicesArr,
							userLocation: _this.userLocation
						}, 'wxapp_notfounddoor_error_log');

						var systemInfo = wx.getSystemInfoSync();
						var is_android_need_location = false;

						console.log('systemInfo.platform', systemInfo.platform);
						console.log('devicesArr.length', devicesArr.length);

						if (devicesArr.length == 0 && systemInfo.platform == 'android') {
							var system_version = systemInfo.system.replace('Android ', '');
							var system_version_arr = system_version.split('.');
							var system_version_big = system_version_arr[0];
							if (system_version_big >= 6 && !_this.userLocation.lng) {
								is_android_need_location = true;
							}
						}
						door.openIngDoor(_this);
					}
					has_reconnect = false;
				}, 6000);

				console.log('蓝牙打开正常', res);
				wx.onBluetoothDeviceFound(function(devices) {
					console.log('找到新的蓝牙设备', devices)

					devicesArr.push(devices['devices'][0].name);
					var dede = JSON.stringify(devices)

					if (devices['devices'][0].name.substr(0, 2) == '05' || devices['devices'][0].name.substr(0, 2) == '0C') {


						console.log('找到蓝牙门禁：' + devices['devices'][0].name);
						console.log('当前蓝牙门禁Device_id：' + realDoorDeviceId);
						var isFind = false;


						if (_this.doorList[device.name.substr(2, 8)]) {
							realDoorDeviceId = device.name.substr(2, 8);
						} else if (_this.doorList[device.name]) {
							realDoorDeviceId = device.name;
						}

						if (realDoorDeviceId) {
							lockData = _this.doorList[realDoorDeviceId].lockData;
							door_id = _this.doorList[realDoorDeviceId].door_id;
							isFind = true;
						}

						if (isFind == false) {
							return;
						}

						//停止搜索不到的事件，且停止搜索
						clearTimeout(doorNotFindTimer);
						isOpened = true;
						door.stopBluetoothDevicesDiscovery(_this);
						//创建蓝牙的连接
						wx.createBLEConnection({
							deviceId: devices['devices'][0]['deviceId'],
							success: function(res) {
								console.log('连接成功蓝牙门禁：' + devices['devices'][0]['name']);
								var deviceId = devices['devices'][0]['deviceId'];
								//获取service
								wx.getBLEDeviceServices({
									// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
									deviceId: deviceId,
									success: function(res) {
										console.log('获取蓝牙设备所有 service:', res.services)

										var servicesLength = res.services.length;

										for (var i = 0; i < servicesLength; i++) {
											if ((res.services[i].uuid.indexOf("fee7") != -1) || (res.services[i].uuid.indexOf("FEE7") != -1)) {
												console.log('device services:', res.services[i].uuid);
												var serviceId = res.services[i].uuid;
												break;
											}
										}

										wx.getBLEDeviceCharacteristics({
											// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
											deviceId: deviceId,
											// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
											serviceId: serviceId,
											success: function(res) {
												console.log('蓝牙设备characteristic(特征值)信息:', res.characteristics)


												var charLength = res.characteristics.length;
												for (var i = 0; i < charLength; i++) {
													if ((res.characteristics[i].uuid.indexOf("fec6") != -1) || (res.characteristics[i].uuid.indexOf(
															"FEC6") != -1)) {
														var characteristicId = res.characteristics[i].uuid;
														break;
													}
												}

												console.log("lockData", lockData);
												if (res.characteristics[0].properties && res.characteristics[0].properties.write) {
													var typedArray = new Uint8Array(lockData.match(/[\da-f]{2}/gi).map(function(h) {
														return parseInt(h, 16);
													}));
													var writeValue = typedArray.buffer;

													console.log('writeValue', writeValue);

													wx.notifyBLECharacteristicValueChange({
														state: true,
														deviceId: deviceId,
														serviceId: serviceId,
														characteristicId: characteristicId,
														success: function(notifyBLECharacteristicValueChangeRes) {
															if (notifyBLECharacteristicValueChangeRes.errCode != '0' &&
																notifyBLECharacteristicValueChangeRes.errMsg !=
																"notifyBLECharacteristicValueChange:ok") {
																app.log_report({
																	door_id: door_id,
																	devicesArr: devicesArr,
																	has_reconnect: has_reconnect,
																	res: notifyBLECharacteristicValueChangeRes,
																	userLocation: _this.userLocation
																}, 'wxapp_notifyBLE_log');
																if (has_reconnect) {
																	wx.hideToast();

																	console.log('writeBLECharacteristicValue error：' + writeValue + '：：：：：', res);
																	door.closeBLEConnection(deviceId);
																	has_reconnect = false;
																} else {
																	wx.closeBLEConnection({
																		deviceId: deviceId,
																		complete: function(res) {
																			console.log('断开与低功耗蓝牙设备的连接', res);
																			wx.closeBluetoothAdapter({
																				complete: function(res) {
																					console.log("关闭蓝牙模块complete", res);
																					has_reconnect = true;
																					/*wx.showLoading({
																					  title: "正在重连开门中",
																					  mask: true
																					});*/
																					setTimeout(function() {
																						door.openIngDoor(_this);
																					}, 500);
																				},
																			});
																		}
																	})
																}

																return false;
															}
															console.log('notifyBLECharacteristicValueChangeRes',
																notifyBLECharacteristicValueChangeRes);
															wx.onBLECharacteristicValueChange(function(CharacteristicValueChangeRes) {
																console.log(
																	`characteristic ${CharacteristicValueChangeRes.characteristicId} has changed, now is ${CharacteristicValueChangeRes.value}`
																);
																console.log(common.ab2hext(CharacteristicValueChangeRes.value));

																door.closeBLEConnection(_this, deviceId);
															});

															setTimeout(function() {
																wx.writeBLECharacteristicValue({
																	// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
																	deviceId: deviceId,
																	// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
																	serviceId: serviceId,
																	// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
																	characteristicId: characteristicId,
																	// 这里的value是ArrayBuffer类型
																	value: writeValue,
																	success: function(res) {
																		has_reconnect = false;
																		isOpened = true;
																		wx.hideToast();
																		/* wx.showLoading({
																		   title: '加载资源中',
																		 })*/
																		console.log('door_id', door_id);
																		if (!_this.hide) {
																			common.post('Login&a=open_door_notice', {
																				door_id: door_id
																			}, function(e) {
																				console.log('e', e);
																				_this.open_door_index = 3;
																				if (e.voice_mp3 && e.voice_mp3 != '' && e.voice_mp3 != null) {
																					door.doorVideo(_this, e.voice_mp3)
																				}
																				wx.hideToast();
																				if (e.url != '' || e.open_lottery_txt != '') {
																					_this.openDoll = e;
																					_this.closeDoll = true;
																				} else {
																					wx.showToast({
																						title: '开门成功',
																						icon: 'success',
																						duration: 3000
																					});
																				}
																				setTimeout(function() {
																					_this.closeDoll = false;
																					_this.open_door_index = 2;
																					autoOpenDoorTimer = setTimeout(function() {
																						door.openIngDoor(_this);
																					}, 10000);
																				}, 3000);
																			});
																		}


																		app.log_report({
																			door_id: door_id,
																			devicesArr: devicesArr,
																			lockData: lockData,
																			writeValue: writeValue,
																			errMsg: res.errMsg,
																			userLocation: _this.userLocation
																		}, 'wxapp_door_log');

																		console.log('writeBLECharacteristicValue success：' + writeValue + '：', res.errMsg);
																	},
																	fail: function(res) {
																		wx.hideToast();
																		console.log('writeBLECharacteristicValue error：' + writeValue + '：：：：：', res);
																		door.closeBLEConnection(_this, deviceId);
																	}
																});
															}, 200);
														}
													});
												} else {
													wx.hideToast();
													console.log('蓝牙设备无法写数据', res.characteristics);
													door.closeBLEConnection(_this, deviceId);
												}
											},
											fail: function(res) {
												wx.hideToast();
												console.log('getBLEDeviceCharacteristics', res);
												app.log_report({
													door_id: door_id,
													devicesArr: devicesArr,
													errorRes: res,
													has_reconnect: has_reconnect,
													userLocation: _this.userLocation
												}, 'wxapp_getBLEDeviceCharacteristics_error_log');

												if (has_reconnect) {
													door.closeBLEConnection(_this, deviceId);
													has_reconnect = false;
												} else {
													wx.closeBLEConnection({
														deviceId: deviceId,
														complete: function(res) {
															console.log('断开与低功耗蓝牙设备的连接', res);
															wx.closeBluetoothAdapter({
																complete: function(res) {
																	console.log("关闭蓝牙模块complete", res);
																	has_reconnect = true;
																	/* wx.showLoading({
																	   title: "正在重连开门中",
																	   mask: true
																	 });*/
																	setTimeout(function() {
																		door.openIngDoor(_this);
																	}, 500);
																},
															});
														}
													})
												}


											}
										})
									},
									fail: function(res) {
										wx.hideToast();
										console.log('getBLEDeviceServicesFail', res);
										app.log_report({
											door_id: door_id,
											devicesArr: devicesArr,
											errorRes: res,
											has_reconnect: has_reconnect,
											userLocation: _this.userLocation
										}, 'wxapp_getServices_error_log');

										if (has_reconnect) {
											/* wx.showModal({
											   title: '失败提示：',
											   content: '获取门禁蓝牙信息（服务）失败，请重试点击开门',
											   showCancel: false
											 });*/
											door.closeBLEConnection(_this, deviceId);
											has_reconnect = false;
										} else {
											wx.closeBLEConnection({
												deviceId: deviceId,
												complete: function(res) {
													console.log('断开与低功耗蓝牙设备的连接', res);
													wx.closeBluetoothAdapter({
														complete: function(res) {
															console.log("关闭蓝牙模块complete", res);
															has_reconnect = true;
															/*wx.showLoading({
															  title: "正在重连开门中",
															  mask: true
															});*/
															setTimeout(function() {
																door.openIngDoor(_this);
															}, 500);
														},
													});
												}
											})
										}
									}
								})
								console.log('createBLEConnectionSuccess', res);
							},
							fail: function(res) {
								wx.hideToast();
								console.log('createBLEConnectionFail', res);
								app.log_report({
									door_id: door_id,
									devicesArr: devicesArr,
									errorRes: res,
									has_reconnect: has_reconnect,
									userLocation: _this.userLocation
								}, 'wxapp_connetion_error_log');
								if (has_reconnect) {
									/* wx.showModal({
									   title: '失败提示：',
									   content: '门禁蓝牙连接失败，请重试点击开门',
									   showCancel: false
									 });*/
									has_reconnect = false;
									door.closeBluetoothAdapter(_this);
								} else {
									wx.closeBluetoothAdapter({
										complete: function(res) {
											console.log("关闭蓝牙模块complete", res);
											has_reconnect = true;
											/*  wx.showLoading({
											    title: "正在重连开门中",
											    mask: true
											  });*/
											setTimeout(function() {
												door.openIngDoor(_this);
											}, 500);
										},
									});
								}
							}
						})
					}
				});
				wx.startBluetoothDevicesDiscovery({
					success: function(res) {
						if (!res.isDiscovering) {
							app.log_report({
								devicesArr: devicesArr,
								errorRes: res,
								userLocation: _this.userLocation
							}, 'wxapp_startDiscoverySuccessError_error_log');
							clearTimeout(doorNotFindTimer);
							setTimeout(function() {
								door.openIngDoor(_this);
							}, 500);
						}
						console.log('startBluetoothDevicesDiscovery:success', res);
					},
					fail: function(res) {
						app.log_report({
							errorRes: res,
							userLocation: _this.userLocation
						}, 'wxapp_startDiscoveryFail_error_log');
						console.log('startBluetoothDevicesDiscovery:fail', res);
					}
				})
			},
			fail: function(res) {
				if (_this.openBlueNum) {
					console.log("您的手机未开启蓝牙，请先开启蓝牙后再点击开门")
					var errMsg = res.errMsg;
					errMsg = errMsg.replace("openBluetoothAdapter:fail", "");
					errMsg = errMsg.replace(/(^\s*)|(\s*$)/g, "");
					if (res.errCode == 10001 || errMsg.indexOf("errCode = 10001") != -1 || errMsg.indexOf("errCode=10001") != -1 ||
						errMsg.indexOf("ble not available") != -1) {
						errMsg = "您的手机未开启蓝牙，请先开启蓝牙后再点击开门";
					}
					var door_tip = _this.open_door;
					door_tip[0] = errMsg;
					_this.open_door_index = 0;
					_this.openBlueNum = true;
					setTimeout(function() {
						door.openBlue(_this);
					}, 1000)

					wx.hideToast();
					/*if(!_this.hide){
					  wx.showModal({
					    title: '提示：',
					    content: errMsg,
					    showCancel: false
					  });
					}*/
				}


			}
		});
	}

}

door.stopBluetoothDevicesDiscovery = (_this) => {
	wx.stopBluetoothDevicesDiscovery({
		success: function(res) {
			console.log("关闭蓝牙搜索成功", res);
		}
	});
}

door.closeBLEConnection = (_this, deviceId) => {
	wx.closeBLEConnection({
		deviceId: deviceId,
		complete: function(res) {
			console.log('断开与低功耗蓝牙设备的连接', res);
			door.closeBluetoothAdapter(_this);
		}
	})
}

door.closeBluetoothAdapter = (_this) => {
	wx.closeBluetoothAdapter({
		success: function() {
			console.log("关闭蓝牙模块成功");
		}
	});
}

door.doorVideo = (_this, res) => {
	console.log(res);
	console.log('播放')
	_this.myaudio.src = res;
	_this.myaudio.autoplay = true;
	_this.myaudio.volume = 1;
	_this.myaudio.obeyMuteSwitch = false;
	_this.myaudio.play();
	_this.myaudio.onPlay(() => {
		console.log('开始播放')
	})
	_this.myaudio.onError((res) => {
		console.log(res.errMsg)
		console.log('播放错区')
	})
}

door.close_door_tip = (_this) => {
	wx.showModal({
		title: '提示',
		content: '将会关闭此次自动开门功能\r\n如需永久关闭请前往开门设置页面。',
		showCancel: true,
		success: function(res) {
			if (res.confirm) {
				_this.open_door_type = false;
				console.log(_this.open_door_type, 'open_door_type')
				app.globalData.open_door_type = false
			} else if (res.cancel) {

			}
		}
	})
}

door.closeAddMySmallProgram = (_this) => {
	_this.addMySmallProgram = true;
	wx.setStorageSync('addMySmallProgram', 'addMySmallProgram');
}


module.exports = door;
